import { Logger } from "./Logger";

const xml2js = require('xml2js');
const request = require('request');
const axios = require('axios');


export class HttpUtil {

    public static request_by_body(url: string, params: object, callback: Function = null) {
        // Logger.log("request_by_body===req=", url, params)
        axios({
            method: 'post',
            url: url,
            timeout: 10000,
            headers: { 'X-Custom-Header': 'abcd' },
            data: params
        }).then(function (response) {
            // Logger.log("request_by_body===response=", response)
            callback && callback(response)
        });
    }

    public static setParams(paramsObj: object): string {
        let resParams = "";
        let nowIndex = 1;
        for (const key in paramsObj) {
            if (paramsObj.hasOwnProperty(key)) {
                let valueStr: any = paramsObj[key];
                if (nowIndex == 1) {
                    resParams += key + "=" + encodeURIComponent(valueStr);
                }
                else {
                    resParams += "&" + key + "=" + encodeURIComponent(valueStr);
                }
                nowIndex += 1;
            }
        }
        // Logger.log("setParams==============", paramsObj, resParams);
        return resParams;
    }

    public static request_by_form(url: string, params: object = null, callback: Function = null) {
        if (params) {
            url = url + "?" + this.setParams(params);
        }
        axios({
            method: 'get',
            url: url,
            timeout: 10000,
            headers: { 'X-Custom-Header': 'abcd' }
        }).then(function (response) {
            // Logger.log("request_by_form===response=", response)
            callback && callback(response)
        });
    }

    public static async request_by_form_promise(url: string, params: object = null): Promise<any> {
        return new Promise((resolve, reject) => {
            this.request_by_form(url, params, (respData) => {
                resolve(respData)
            })
        })
    }

    public static async request_by_body_promise(url: string, params: object = null): Promise<any> {
        return new Promise((resolve, reject) => {
            this.request_by_body(url, params, (respData) => {
                resolve(respData)
            })
        })
    }




}